package com.xiaoyu.lanling.feature.videomatch.service

import `in`.srain.cube.util.CLog
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.data.UserData
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.data.NotificationData
import com.xiaoyu.lanling.event.voicematch.VoiceMatchServiceForegroundEvent
import com.xiaoyu.lanling.feature.videomatch.util.VideoMatchNotificationUtils
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lib_av.datamodel.CallParams

class VideoMatchCallService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            stop()
            return START_NOT_STICKY
        }
        val isCaller = intent.getBooleanExtra(Constant.IntentKey.KEY_CHAT_CALL_IS_CALLER, false)
        val callParams = intent.getSerializableExtra(Constant.IntentKey.KEY_CHAT_CALL_CALL_PARAM) as CallParams
        showVideoMatchCallNotification(callParams, isCaller)
        return START_REDELIVER_INTENT
    }

    private fun showVideoMatchCallNotification(callParams: CallParams, isCaller: Boolean) {
        val isReceive = UserData.getInstance().isSelf(callParams.toUser.uid)
        val intent = Router.instance.createVideoMatchCallVideoIntent(AppContext.getContext(), callParams, isCaller)
        val title = AppContext.getString(R.string.voice_match_notification_title)
        val text: CharSequence = VideoMatchNotificationUtils.getNotificationText(isReceive)
        val notification = buildNotification(title, text, intent)
        startForeground(NotificationData.NotificationId.CALL_VIDEO_MATCH, notification)
        VoiceMatchServiceForegroundEvent().post()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onDestroy() {
        CLog.i(TAG, "onDestroy()")
        super.onDestroy()
        stopForeground(true)
    }

    private fun buildNotification(title: CharSequence, text: CharSequence, activityIntent: Intent): Notification {
        val pendingIntent = PendingIntent.getActivity(AppContext.getContext(), 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        return VideoMatchNotificationUtils.instance.buildNotification(title, text, pendingIntent)
    }

    private fun stop() {
        stopForeground(true)
        stopSelf()
    }

    companion object {
        val TAG: String = VideoMatchCallService::class.java.simpleName
    }
}